package net.dodoman.md5;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;

public class Md5Util {
	String getMD5(String filePath) {

		String MD5 = "";

		try {

			// File file = new File(filePath);

			// FileInputStream fos = new FileInputStream(file);

			BufferedRandomAccessFile oSavedFile = new BufferedRandomAccessFile(
					filePath, "rw");

			java.security.MessageDigest alga = java.security.MessageDigest
					.getInstance("MD5");

			byte[] buffer = new byte[1024];// 设置填充大小

			int read;// 实际读取的字节数

			while ((read = oSavedFile.read(buffer, 0, 1024)) > 0) {

				alga.update(buffer, 0, read);

			}
			byte[] digesta = alga.digest();

			for (int i = 0; i < digesta.length; i++) {

				MD5 += Integer.toHexString(
						(0x000000ff & digesta[i]) | 0xffffff00).substring(6);

			}

		} catch (NoSuchAlgorithmException e1) {
			// TODO 自动生成 catch 块
			e1.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}

		return MD5;
	}

	/**
	 * 文件块的md5
	 * 
	 * 如果对一个文件进行了分块，需要知道每个文件块的md5可以采取下面的方法.i代表块开始的位置,BlockSize为每块的实际大小
	 */
	String getMD51(String filePath,long i,long BlockSize) {
		  String MD5 = "";
		  try {
		      //File file = new File(filePath);
		      //FileInputStream fos = new FileInputStream(file);
		     BufferedRandomAccessFile oSavedFile = new BufferedRandomAccessFile(
		     filePath, "rw");
		   java.security.MessageDigest alga = java.security.MessageDigest
		     .getInstance("MD5");
		   byte[] buffer = new byte[1024];// 设置填充大小
		   int read;//实际读取的字节数
		   oSavedFile.seek(i);
		   long count=0;
		   while ((read = oSavedFile.read(buffer, 0, 1024)) > 0) {
		   count += read;
		   alga.update(buffer, 0, read);
		     //到达该块末尾
		     if (count == Blocksize) {
		      break;
		   }
		   byte[] digesta = alga.digest();

		   for (int j = 0; j < digesta.length; j++) {
		    MD5 += Integer.toHexString(
		      (0x000000ff & digesta[j]) | 0xffffff00).substring(6);

		   }
		  } catch (NoSuchAlgorithmException e1) {
		   e1.printStackTrace();
		  } catch (FileNotFoundException e) {
		   e.printStackTrace();
		  } catch (IOException e) {
		   e.printStackTrace();
		  }
		  return MD5;
		 } 
		}
}
